package com.buaa.rental.AdminController;

import com.buaa.rental.Dao.CommonRep;
import com.buaa.rental.Dao.User;
import com.buaa.rental.Dao.User.Role;
import com.buaa.rental.Service.UserService;
import com.buaa.rental.Util.CodeException;
import com.buaa.rental.Util.DataFormat;
import com.buaa.rental.Util.MyAnnotations.Authorization;
import com.buaa.rental.Util.MyAnnotations.CurrentUser;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api/admin/")
public class AdminUserController
{

	@Autowired
	private UserService userService;

	@Authorization(role = Role.admin)
	@PostMapping("addUser")
	public CommonRep addWorker(@CurrentUser User cu, @RequestBody @Valid User user,
			BindingResult res) throws CodeException
	{
		if (res.hasErrors())
		{
			throw new CodeException("101", DataFormat.bindingErrorsFormat(res));
		}
		if (user.role != Role.worker && user.role != Role.user)
		{
			throw new CodeException("101", "需要指定用户角色");
		}
		try
		{
			userService.register(user);
		} catch (Exception e)
		{
			throw new CodeException("101", e.getMessage());
		}
		return new CommonRep();
	}



	@Authorization(role = Role.admin)
	@PostMapping("changeUserInfo")
	public CommonRep changeUserInfo(@RequestBody @Valid User user,
			BindingResult res) throws CodeException
	{
		if (res.hasErrors())
		{
			throw new CodeException("101", DataFormat.bindingErrorsFormat(res));
		}
		if (user.uid == 0)
		{
			throw new CodeException("101", "参数错误");
		}
		User cu = userService.getUserByUid(user.uid);
		if (user.name != null)
		{
			cu.name = user.name;
		}
		if (user.age != 0)
		{
			cu.age = user.age;
		}
		if (user.province != null)
		{
			cu.province = user.province;
		}
		if (user.district != null)
		{
			cu.district = user.district;
		}
		if (user.phoneNum != null)
		{
			cu.phoneNum = user.phoneNum;
		}
		if (user.personIntro != null)
		{
			cu.personIntro = user.personIntro;
		}
		if (user.avatar != null)
		{
			cu.avatar = user.avatar;
		}
		if (user.psw != null)
		{
			cu.psw = user.psw;
		}
		userService.updateUser(cu);
		return new CommonRep();
	}

	@Authorization(role = Role.admin)
	@GetMapping("getAllWorker")
	public CommonRep getAllWorker(){
		CommonRep rep = new CommonRep();
		rep.setData(userService.getAllWorker());
		return rep;
	}

	@Authorization(role = Role.admin)
	@GetMapping("getAllUser")
	public CommonRep getAllUser(){
		CommonRep rep = new CommonRep();
		rep.setData(userService.getUsers());
		return rep;
	}
}
